package com.example.schedule;

import com.example.channel.BootNettyChannel;
import com.example.channel.BootNettyChannelCache;
import com.example.instance.BootNettyServer;
import com.example.service.ItrafficFlowService;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: ItrafficFlowTask
 * @Author : 13736
 * @Date :2023/7/8  13:41
 * @Description: TODO
 * @Version :1.0
 */
@Slf4j
@Component
public class ItrafficFlowTask {

    @Resource
    private ItrafficFlowService itrafficFlowService;
    @Resource
    private BootNettyServer bootNettyServer;

    @Autowired
    private ThreadPoolTaskExecutor executor;
    //@Scheduled(cron = "0/10 * * * * ?")
    public void task(){

        if (BootNettyChannelCache.size() > 0) {
            String data = itrafficFlowService.getXmlStr();
            log.info("Netty-Server-----连接通道数量: {}", BootNettyChannelCache.size());
            log.info("Netty-Server 开始向客户端发送消息：{}", data);
            for (Map.Entry<String, BootNettyChannel> entry : BootNettyChannelCache.channelMapCache.entrySet()) {
                BootNettyChannel bootNettyChannel = entry.getValue();
                if (bootNettyChannel != null && bootNettyChannel.getChannel().isOpen()) {
                    bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(data.getBytes()));
                }
            }
        }
    }

    //@Scheduled(cron = "0/10 * * * * ?")
    public void task2(){
        for(int i = 0;i<20;i++){
            executor.execute(()->{
                List<String> xmlList = new ArrayList<>();
                for(int j=0;j<20;j++){
                    String data = itrafficFlowService.getXmlStr();
                    xmlList.add(data);
                }
                xmlList.forEach(item->bootNettyServer.sendMsg(item));
            });
        }
    }

    //@Scheduled(cron = "0/10 * * * * ?")
    public void task3(){
        for (int i = 0; i < 20; i++) {
            List<String> xmlList = new ArrayList<>();
            for (int j = 0; j < 20; j++) {
                String data = itrafficFlowService.getXmlStr();
                xmlList.add(data);
            }
            xmlList.forEach(item -> bootNettyServer.sendMsgSync(item));

        }
    }
}
